package com.ruan.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruan.common.R;
import com.ruan.mapper.ParticipantMapper;
import com.ruan.pojo.Employee;
import com.ruan.pojo.Participant;
import com.ruan.pojo.Project;
import com.ruan.pojo.ProjectAssignments;
import com.ruan.service.EmployeeService;
import com.ruan.service.ParticipantService;
import com.ruan.service.ProjectAssignmentsService;
import com.ruan.service.ProjectService;
import com.sun.xml.bind.v2.TODO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/projectAssignments")
public class ProjectAssignmentsController {
    @Autowired
    private ProjectAssignmentsService projectAssignmentsService;

    @Autowired
    private ProjectService projectService;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private ParticipantMapper participantMapper;

    @Autowired
    private ParticipantService participantService;

    //新增项目分配记录
    @PostMapping("/saveAssignmentInfo")
    @Transactional
    public R<String> save(@RequestBody ProjectAssignments projectAssignments){
        log.info("新增项目分配记录，项目分配信息：{}",projectAssignments.toString());

        //项目表要填充之前空着的项目负责人id
        Project project = projectService.getById(projectAssignments.getProjectId());
        Employee employee = null;
        if(projectAssignments.getEmployeeId() != null){
            employee = employeeService.getById(projectAssignments.getEmployeeId());
        }
        if(employee != null && !employee.getStatus().equals("离职")){
//            System.out.println("projectAssignments.getEmployeeId()是"+projectAssignments.getEmployeeId());
            project.setEmployeeId(projectAssignments.getEmployeeId());
        }else{
            //回滚上一个addParticipant的逻辑
//            System.out.println("回滚上一个addParticipant的逻辑");
            LambdaQueryWrapper<Participant> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Participant::getProjectId, projectAssignments.getProjectId());
            participantMapper.delete(queryWrapper);
            String employeeName = employee.getName();
            if (employeeName == null || employeeName.isEmpty()) {
                return R.error("负责人信息缺失，请重新选择");
            } else {
                return R.error("负责人" + employeeName + "已离职，请重新选择");
            }
        }

        if(project != null){
            projectService.updateById(project);
        }else {
            return R.error("项目不存在");
        }

        //前端选择负责人时，同时也会给下面的参与员工插入自己的信息作为参与人员，
        // 但是有可能有人把它故意取消，所以需要判断一下，负责人是否已经在项目参与表里了
        LambdaQueryWrapper<Participant> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(Participant::getProjectId, projectAssignments.getProjectId());
        queryWrapper.eq(Participant::getEmployeeId, projectAssignments.getEmployeeId());
// 检查是否有数据匹配
        // 查询匹配的数量
        int count = participantMapper.selectCount(queryWrapper);
        //System.out.println("补充负责人的信息count:"+count);
        if (count == 0) {
            //System.out.println("补充负责人的信息");
            // 如果项目参与表里查不到该项目的该负责人参与信息，则插入补充负责人的信息到项目参与表里
            Participant participant = new Participant();
            participant.setProjectId(projectAssignments.getProjectId());
            participant.setEmployeeId(projectAssignments.getEmployeeId());
            //更新参与人数
            //TODO 空指针
            projectAssignments.setParticipants(projectAssignments.getParticipants()+1);
            //System.out.println("现在插入的是："+participant);
            participantMapper.insert(participant);
        }
        LambdaQueryWrapper<ProjectAssignments> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(ProjectAssignments::getProjectId, projectAssignments.getProjectId());
        queryWrapper1.eq(ProjectAssignments::getEmployeeId, projectAssignments.getEmployeeId());
        int count1 = projectAssignmentsService.count(queryWrapper1);
        //System.out.println("有多少条count1"+count1);
        if(count1 > 1){
            //删除多余的，只留下一条
            // 查询符合条件的所有记录
            List<ProjectAssignments> list = projectAssignmentsService.list(queryWrapper1);
            //System.out.println("list"+list);
            // 保留 list 中的第一条记录，其他的删除
            // 确保保留的记录是否正确
            ProjectAssignments recordToKeep = list.get(0);
            // 删除多余的记录
            for (ProjectAssignments assignment : list) {
                if (!assignment.equals(recordToKeep)) {
                    projectAssignmentsService.removeById(assignment.getId());
                }
            }
            return R.success("项目分配成功");
        }else if(count1 == 1){
            return R.success("项目已经分配，请勿重复添加");
        }
        //把这个项目分配对象存进去
        projectAssignmentsService.save(projectAssignments);

//        projectToolAssignmentService.save()
//save方法继承自mybatis-plus的父接口IService（看看application.yml文件）,可以直接调用
        return R.success("项目分配成功");
    }
}
